const crypto = require("crypto");
const fs = require("fs");
const { PRIVATE_PATH, PUBLIC_PATH } = require("../config/path");
/**生成私钥和公钥 */
const generateKeyPair = () => {
  return new Promise((resolve, reject) => {
    crypto.generateKeyPair(
      "rsa",
      {
        modulusLength: 2048,
        publicKeyEncoding: {
          type: "spki",
          format: "pem",
        },
        privateKeyEncoding: {
          type: "pkcs8",
          format: "pem",
        },
      },
      (err, publicKey, privateKey) => {
        if (err) {
          reject(err);
        } else {
          resolve({ publicKey, privateKey });
        }
      }
    );
  });
};
/**判断私钥和公钥文件是否存在 */
function checkFileExist() {
  try {
    fs.statSync(PRIVATE_PATH);
  } catch (error) {
    generateKeyPair()
      .then(({ publicKey, privateKey }) => {
        try {
          fs.writeFileSync(PRIVATE_PATH, privateKey);
          console.log("生成私钥成功");
        } catch (error) {
          console.log("生成私钥失败", error);
        }
        try {
          fs.writeFileSync(PUBLIC_PATH, publicKey);
          console.log("生成公钥成功");
        } catch (error) {
          console.log("生成公钥失败", error);
        }
      })
      .catch((error) => {
        console.error("Error generating key pair:", error);
      });
  }
}
checkFileExist();
